#include "JsbBridgeTest.h"
#import <Foundation/Foundation.h>
#include "cocos/platform/apple/JsbBridgeWrapper.h"
#import <Photos/Photos.h>
#import "ImagePicker.h"

@implementation JsbBridgeTest {
    UIWindow *_window;
    JsbBridgeWrapper *_jsb;
}
static JsbBridgeTest* instance = nil;
static NSString* APPID = nil;
+(instancetype)sharedInstance{
    static dispatch_once_t pred = 0;
    dispatch_once(&pred, ^{
        instance = [[super allocWithZone:NULL]init];
    });
    return instance;
}

+(id)allocWithZone:(struct _NSZone *)zone{
    return [JsbBridgeTest sharedInstance];
}

-(id)copyWithZone:(struct _NSZone *)zone{
    return [JsbBridgeTest sharedInstance];
}

- (void)setupWithAppDelegate:(UIWindow *)window {
    _window = window;
    
    _jsb = [JsbBridgeWrapper sharedInstance];
    
    [_jsb addScriptEventListener:@"JSToIos" listener:^void(NSString* arg) {
        if (![arg containsString:@"###!!!"]) {
            NSLog(@"JS 参数格式错误：缺少 '###!!!'");
            return; // 退出 block，不执行后续逻辑
        }
        
        if ([arg containsString:@"cocosString###!!!"]) {
            [JsbBridgeTest cocosString:arg];
            return; // 退出 block，不执行后续逻辑
        }
        
        NSArray<NSString *> *parts = [arg componentsSeparatedByString:@"###!!!"];
        if (parts.count < 2) {
            NSLog(@"参数格式错误，无法解析");
            return;
        }
        NSString *funName = parts[0];
        NSString *funArg = parts[1];
        
        if ([funName isEqualToString:@"lockScreenLandscape"]) {
            [JsbBridgeTest setOrientation:funArg];
        }
        
        if ([funName isEqualToString:@"wxLogin"]) {
            [JsbBridgeTest wxLogin:funArg];
        }
        if ([funName isEqualToString:@"saveToFile"]) {
            [JsbBridgeTest saveToFile:funArg];
        }
        if ([funName isEqualToString:@"getAppSystemInfo"]) {
            [JsbBridgeTest getAppSystemInfo:funArg];
        }
        if ([funName isEqualToString:@"selectFile"]) {
            [JsbBridgeTest selectFile:funArg];
        }
    }];
    
    
}

+(void)cocosString:(NSString *)arg{
    NSString *jsonString = [arg stringByReplacingOccurrencesOfString:@"cocosString###!!!" withString:@""];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    APPID = dic[@"wxAppId"];
    [JsbBridgeTest regToWx:dic[@"iosuniversalLink"]];
}

+(void)regToWx: (NSString *)unLink {
    
}

+(void)sendToJs:(NSString *)type data:(id)data {
    NSString *jsonString = @"";
    // 1. 构建 JSON 数据（NSDictionary）
    NSDictionary *jsonDict = @{
        @"type": type,
        @"data": data ?: [NSNull null]
    };

    // 2. 转换为 JSON 数据（NSData）
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                      options:NSJSONWritingPrettyPrinted
                                                        error:&error];

    // 3. 转换为 NSString
    if (jsonData) {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//        NSLog(@"JSON 字符串:\n%@", jsonString);
        [[self sharedInstance]->_jsb dispatchEventToScript:@"IosToJS" arg:jsonString];
    } else {
        NSLog(@"JSON 转换失败: %@", data);
    }
}

+(void)fastSetetOrientation: (UIWindow *)window arg:(NSString *)arg {
    [self sharedInstance]->_window = window;
    [JsbBridgeTest setOrientation:arg];
}

+(void)setOrientation:(NSString *)arg {
    if (@available(iOS 16.0, *)) {
        NSLog(@"------iOS 16.0 +----------");
        UIWindowScene *windowScene = [self sharedInstance]->_window.windowScene;
        UIWindowSceneGeometryPreferencesIOS *preferences =
            [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait];
        
        if ([arg isEqualToString:@"2"]) {
            //NSLog(@"方向：%s",arg);
            preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskLandscapeRight];
        }
        [windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:nil];
        return;
    }
    if ([arg isEqualToString:@"1"]) {
        [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
        return;
    }
    if ([arg isEqualToString:@"2"]) {
        [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
        return;
    }
}

+(void)wxLogin:(NSString *)arg
{
    
    
}

+ (void)saveToFile:(NSString *)arg{
    NSData *jsonData = [arg dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    NSString *imagePath = dic[@"filePath"];
    
    // 检查文件是否存在
    if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
        [JsbBridgeTest sendToJs:@"errAlert" data:@"文件不存在！"];
        NSLog(@"文件不存在:%@", arg);
        return;
    }
    
    
    
    // 获取 UIImage 对象
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    if (!image) {
        [JsbBridgeTest sendToJs:@"errAlert" data:@"图片对象不存在！"];
        return;
    }
    
    // 检查当前权限状态
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    if (status == PHAuthorizationStatusAuthorized) {
        // 已有权限，直接保存
        [JsbBridgeTest saveImageToAlbum:image];
    } else if (status == PHAuthorizationStatusNotDetermined) {
        // 请求权限
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [JsbBridgeTest saveImageToAlbum:image];
            } else {
                [JsbBridgeTest sendToJs:@"errAlert" data:@"图片保存失败！"];
            }
        }];
    } else {
        [JsbBridgeTest sendToJs:@"errAlert" data:@"没有权限访问相册！"];
    }

}

// 实际保存图片的辅助方法
+ (void)saveImageToAlbum:(UIImage *)image{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [JsbBridgeTest sendToJs:@"sendToNativeReturn" data:@"1"];
                // 可以在这里添加UI提示
            } else {
                [JsbBridgeTest sendToJs:@"errAlert" data:@"保存失败！"];
                // 可以在这里添加错误提示
            }
        });
    }];
}

+ (void)getAppSystemInfo:(NSString *)arg {
    NSString *bundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSString *shortVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSDictionary *jsonDict = @{
        @"versionCode": bundleVersion,
        @"versionName": shortVersionString
    };
    [JsbBridgeTest sendToJs:@"getAppSystemInfoReturn" data:jsonDict];
}
+ (void)selectFile:(NSString *)arg {
    [[ImagePicker sharedInstance] pickImageFromGallery];
}

@end
